<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row shadow="hover" v-show="showSearch" class="ml10">
				<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
					<el-form-item label="房间号" prop="roomNumber">
						<el-input placeholder="请输入房间号" clearable style="max-width: 180px" v-model="state.queryForm.roomNumber" />
					</el-form-item>
          <el-form-item label="楼宇" prop="buildingId">
            <el-select v-model="state.queryForm.buildingId" placeholder="请选择楼宇" clearable @change="getUnit">
              <el-option v-for="building in buildingList" :key="building.buildingId" :label="building.buildingName" :value="building.buildingId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单元" prop="unitId">
            <el-select v-model="state.queryForm.unitId" placeholder="请先选择楼宇" clearable>
              <el-option v-for="unit in unitList" :key="unit.unitId" :label="unit.unitName" :value="unit.unitId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用途" prop="purposeId">
            <el-select v-model="state.queryForm.purposeId" placeholder="请选择用途" clearable>
              <el-option v-for="purpose in property_room_purpose" :key="purpose.value" :label="purpose.label" :value="purpose.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="query" class="ml10" icon="search" type="primary">
              查询
            </el-button>
            <el-button @click="onOpenAddMenu" class="ml10" icon="plus" type="primary">
              新增
            </el-button>
            <el-button @click="resetQuery" icon="Refresh">
              重置
            </el-button>
            <el-button @click="handleDelete(selectObjs, selectRoom)" icon="Refresh" :disabled="multiple">
              删除
            </el-button>
            <el-button @click="onOpenRelatedUser(selectObjs[0], true)" class="ml10" type="primary" :disabled="single">
              已关联用户
            </el-button>
            <el-button @click="onOpenUnRelatedUser(selectObjs[0], true)" class="ml10" type="primary" :disabled="single">
              未关联用户
            </el-button>
          </el-form-item>
				</el-form>
			</el-row>
      <el-table
          :data="state.dataList"        style="width: 100%"
          v-loading="state.loading"
          @selection-change="handleSelectionChange"
          border
          :cell-style="tableStyle.cellStyle"
          :header-cell-style="tableStyle.headerCellStyle"
      >
        <!-- 根据实际字段调整表格列 -->
        <el-table-column type="selection" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="序号" type="index" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="房间号" prop="roomNumber" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="楼宇名称" prop="buildingName" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="单元名称" prop="unitName" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="楼层" prop="floorName" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="用途" prop="purposeId" show-overflow-tooltip width="auto">
          <template #default="scope">
            <dict-tag :options="property_room_purpose" :value="scope.row.purposeId" />
          </template>
        </el-table-column>
        <el-table-column label="建筑面积" prop="buildingArea" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="使用面积" prop="usingArea" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="住户数" prop="residents" show-overflow-tooltip width="auto">
          <template #default="scope">
            <el-link
                v-if="scope.row.residents > 0"
                type="primary"
                @click="onOpenRelatedUser(scope.row.roomId, false)"
            >
              {{ scope.row.residents }}
            </el-link>
            <span v-else>{{ scope.row.residents }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="操作" width="auto">
          <template #default="scope">
            <el-button icon="edit-pen" @click="onOpenEditRoom(scope.row)" text type="primary">
              编辑
            </el-button>
            <el-button icon="delete" @click="handleDelete([scope.row.roomId], [scope.row.roomNumber])" text type="primary">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
          @current-change="currentChangeHandle"
          @size-change="sizeChangeHandle"
          v-bind="state.pagination"
      />
		</div>
		<MenuDialog @refresh="getDataList()" ref="menuDialogRef" />
    <ResidentDialog @refresh1="getDataList()" ref="menuDialogRef1" />
	</div>
</template>

<script lang="ts" name="systemMenu" setup>
import {BasicTableProps, useTable} from '/@/hooks/table';
import {useMessage, useMessageBox} from '/@/hooks/message';
import {deleteRoom, getBuildingList, getUnitList, roomList} from '/@/api/room/room';
import {onMounted} from "vue";
import {useDict} from "/@/hooks/dict";
import {useRoute} from "vue-router";
// 引入组件
const MenuDialog = defineAsyncComponent(() => import('./form.vue'));
const ResidentDialog = defineAsyncComponent(() => import('./residentForm.vue'));
const route = useRoute();

// 定义变量内容
const tableRef = ref();
const menuDialogRef = ref();
const menuDialogRef1 = ref();
const queryRef = ref();
const showSearch = ref(true);
const state: BasicTableProps = reactive<BasicTableProps>({
	pageList: roomList, // H
	queryForm: {
    roomNumber: undefined,
    buildingId: undefined,
    unitId: undefined,
    floorId: undefined,
    purposeId: undefined
	},
	isPage: true,
});
const { property_room_purpose } = useDict('property_room_purpose');
const buildingList = ref([]);
const unitList = ref([]);

// 多选rows
const selectObjs = ref([]) as any;
const selectRoom = ref([]) as any;
// 是否可以多选
const multiple = ref(true);
//单选判断
const single = computed(() => selectObjs.value.length !== 1);

const { getDataList, tableStyle, currentChangeHandle, sizeChangeHandle } = useTable(state);

onMounted(() => {
  getBuilding();
  state.queryForm.floorId = route.query?.floorId;
  getDataList();
});

// 打开新增菜单弹窗
const onOpenAddMenu = (row?: any) => {
	menuDialogRef.value.openDialog("新增房间", row);
};
// 打开编辑菜单弹窗
const onOpenEditRoom = (row: any) => {
	menuDialogRef.value.openDialog("修改房间", row);
};

//打开关联人员弹窗
const onOpenRelatedUser = (row: any, judge: boolean) => {
  menuDialogRef1.value.openResidentDialog("关联人员", "取消关联", row, judge);
}
//打开未关联人员弹窗
const onOpenUnRelatedUser = (row: any, judge: boolean) => {
  menuDialogRef1.value.openResidentDialog("未关联人员", "关联", row, judge);
}

// 多选事件
const handleSelectionChange = (objs: { roomId: string, roomNumber: string }[]) => {
  selectObjs.value = objs.map(({ roomId }) => roomId);
  selectRoom.value = objs.map(({ roomNumber }) => roomNumber);
  multiple.value = !objs.length;
};



const toggleExpand = (children: any[], unfold = true) => {
	for (const key in children) {
		tableRef.value?.toggleRowExpansion(children[key], unfold);
		if (children[key].children) {
			toggleExpand(children[key].children!, unfold);
		}
	}
};

// 搜索事件
const query = () => {
  state.dataList = [];
  getDataList();
};
// 加载楼宇
const getBuilding = async () => {
  const res = await getBuildingList();
  buildingList.value = res.data.data;
};

// 根据楼宇加载单元
const getUnit = async (buildingId: Number) => {
  const res = await getUnitList(buildingId);
  unitList.value = res.data.data;
};

// 清空搜索条件
const resetQuery = () => {
  state.queryForm = {
    roomNumber: undefined,
    buildingId: undefined,
    unitId: undefined,
    floorId: undefined,
    purposeId: undefined
  }
  state.dataList = [];
  unitList.value = [];
  getDataList();
};

// 删除操作
const handleDelete = async (ids: Number[], rooms: string[]) => {
	try {
		await useMessageBox().confirm('您确定要删除' + rooms + '房间吗');
	} catch {
		return;
	}

	try {
		await deleteRoom(ids);
		getDataList();
		useMessage().success('删除成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
</script>
